import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';
import { FriendStatus } from '@/app/types/friend';

export async function POST(req: NextRequest) {
  try {
    const userId = getUserId(req);
    console.log('userId', userId);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { friendId } = await req.json();

    if (!friendId) {
      return NextResponse.json({ error: '缺少 friendId' }, { status: 400 });
    }

    if (userId === friendId) {
      return NextResponse.json({ error: '不能添加自己为好友' }, { status: 400 });
    }

    // 检查对方用户是否存在
    const friendExists = await prisma.user.findUnique({ where: { id: friendId } });
    if (!friendExists) {
      return NextResponse.json({ error: '该用户不存在' }, { status: 404 });
    }

    // 检查是否被对方拉黑
    const isBlocked = await prisma.block.findUnique({
      where: {
        userId_blockedUserId: {
          userId: friendId,
          blockedUserId: userId,
        },
      },
    });

    if (isBlocked) {
      return NextResponse.json({ error: '无法发送好友请求，可能已被对方拉黑' }, { status: 403 });
    }

    const existingFriendship = await prisma.friend.findFirst({
      where: {
        OR: [
          { userId: userId, friendId: friendId },
          { userId: friendId, friendId: userId },
        ],
      },
    });

    if (existingFriendship) {
      if (existingFriendship.status === FriendStatus.ACCEPTED) {
        return NextResponse.json({ error: '你们已经是好友了' }, { status: 400 });
      }
      if (existingFriendship.status === FriendStatus.PENDING) {
        if (existingFriendship.userId === userId) {
          return NextResponse.json({ error: '你已经发送过好友请求，请耐心等待' }, { status: 400 });
        } else {
          return NextResponse.json({ error: '对方已经向你发送了好友请求，请直接同意' }, { status: 400 });
        }
      }
    }

    const newFriendRequest = await prisma.friend.create({
      data: {
        userId: userId,
        friendId: friendId,
        status: FriendStatus.PENDING,
      },
    });

    return NextResponse.json({ message: '好友请求已发送', data: newFriendRequest }, { status: 201 });
  } catch (error: any) {
    console.error('发送好友请求失败:', error);
    return NextResponse.json({ error: '服务器内部错误' }, { status: 500 });
  }
}